<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2022-06-23
 * Time: 11:13:24
 * Info: 系统设置
 */

namespace app\admin\controller\system;

use app\admin\annotation\ControllerAnnotation;
use app\admin\annotation\NodeAnotation;
use app\admin\controller\CommonController;
use support\Request;
use app\common\model\Config as ConfigModel;
use app\common\service\CacheService;

/**
 * @ControllerAnnotation(title="系统设置")
 * Class Node
 * @package app\admin\controller\system
 */
class ConfigController extends CommonController
{

    /**
     * @NodeAnotation(title="系统设置")
     */
    public function index(Request $request)
    {
        $datalist = ConfigModel::select()->toArray();
        $data     = array_column($datalist, 'value', 'name');
        if ( ! empty($data['dingxiang_appSecret'])) {
            $data['dingxiang_appSecret'] = half_replace($data['dingxiang_appSecret']);
        }
        $data['ueditor_icon'] = array_filter(explode(',', $data['ueditor_icon']));
        $ueditorIcon          = config('ueditor_icon');

        //附件保存方式：
        $uploadModes = ConfigModel::UPLOAD_MODES;

        return view('config/index', ['data' => $data, 'ueditor_icon' => $ueditorIcon, 'upload_modes' => $uploadModes]);
    }

    /**
     * @NodeAnotation(title="保存设置")
     */
    public function save(Request $request)
    {
        if ($request->isPost()) {
            $param = $request->all();
            if ( ! empty($param['dingxiang_appSecret']) && strstr($param['dingxiang_appSecret'], '**')) {
                unset($param['dingxiang_appSecret']);
            }
            if ( ! empty($param['ueditor_icon'])) {
                $param['ueditor_icon'] = implode(',', $param['ueditor_icon']);
            } else {
                $param['ueditor_icon'] = '';
            }
            foreach ($param as $key => $value) {
                $arr[$key] = $value;
                $value     = htmlspecialchars($value);
                ConfigModel::strict(false)->where(['name' => $key])->data(['value' => $value])->update();
            }
            //清除缓存
            CacheService::updateSystemConfig();

            return $this->success('保存成功');
        }
    }

    /**
     * @NodeAnotation(title="自定义配置")
     */
    public function customConfig()
    {
        $data = ConfigModel::where('type', '99')->select();

        return view('config/custom_config', ['data' => $data]);

    }

    /**
     * @NodeAnotation(title="添加自定义配置")
     */
    public function custom_config_add(Request $request)
    {
        if ($request->isPost()) {
            $param = $request->all();
            $cha   = ConfigModel::where('name', $param['name'])->find();
            if (is_array($cha)) {
                return error_json('配置名称已存在，请修改');
            }
            if ($param['fieldtype'] == "radio" || $param['fieldtype'] == "select") {
                $setting = json_encode(explode('|', rtrim($param['setting'][$param['fieldtype']], '|')),
                    JSON_UNESCAPED_UNICODE);
                $setting = str_replace("：", ":", $setting);
            } else {
                $setting = "";
            }
            $data = [
                'name'      => $param['name'],
                'fieldtype' => $param['fieldtype'],
                'type'      => 99,
                'title'     => $param['title'],
                'status'    => 1,
                'value'     => $param['value'][$param['fieldtype']],
                'setting'   => $setting
            ];
            try {
                ConfigModel::insert($data);
            } catch (\Exception $e) {
                return error_json('操作失败<br>'.$e->getMessage());
            }
            //清除缓存
            CacheService::updateSystemConfig();

            return $this->success('操作成功');

        }

        return view('config/custom_config_add');
    }

    /**
     * @NodeAnotation(title="修改自定义配置")
     */
    public function custom_config_edit(Request $request)
    {
        $id   = $request->input('id');
        $data = ConfigModel::where('id', $id)->where('type', 99)->find();
        if (empty($data)) {
            return error_json('获取数据失败');
        }
        if ($request->isPost()) {
            $param = $request->all();
            if ($data['fieldtype'] == 'radio' || $data['fieldtype'] == 'select') {
                $data = [
                    'title'  => $param['title'],
                    'value'  => $param['value'],
                    'status' => $param['status']
                ];
            } else {
                $data = [
                    'title'  => $param['title'],
                    'value'  => $param['value'][$data['fieldtype']],
                    'status' => $param['status']
                ];
            }

            ConfigModel::where('id', $param['id'])->data($data)->update();
            //清除缓存
            CacheService::updateSystemConfig();

            return $this->success('修改成功');
        }
        if ($data['fieldtype'] == 'radio') {
            $setting      = json_decode($data['setting'], true);
            $setting_data = "";
            foreach ($setting as $k => $v) {
                if (strstr($v, ':')) {
                    $v2           = $v;
                    $v            = explode(":", $v2)[0];
                    $k            = explode(":", $v2)[1];
                    $checked      = $data['value'] == $k ? "checked" : '';
                    $setting_data .= '<input type="radio" name="value" value="'.$k.'" title="'.$v.'" '.$checked.'>';
                } else {
                    $checked      = $data['value'] == $v ? "checked" : '';
                    $setting_data .= '<input type="radio" name="value" value="'.$v.'" title="'.$v.'" '.$checked.'>';
                }
            }
        } elseif ($data['fieldtype'] == 'select') {
            $setting      = json_decode($data['setting'], true);
            $setting_data = "";
            foreach ($setting as $k => $v) {
                if (strstr($v, ':')) {
                    $v2           = $v;
                    $v            = explode(":", $v2)[0];
                    $k            = explode(":", $v2)[1];
                    $selected     = $data['value'] == $k ? "selected" : '';
                    $setting_data .= '<option value="'.$k.'" '.$selected.'>'.$v.'</option>';
                } else {
                    $selected     = $data['value'] == $v ? "selected" : '';
                    $setting_data .= '<option value="'.$v.'" '.$selected.'>'.$v.'</option>';
                }

            }
        } else {
            $setting_data = '';
        }

        return view('config/custom_config_edit', ['data' => $data, 'setting_data' => $setting_data]);
    }

    /**
     * @NodeAnotation(title="删除自定义配置")
     */
    public function custom_config_delete(Request $request)
    {
        $id = $request->input('id');
        ConfigModel::where('id', $id)->delete();
        //清除缓存
        CacheService::updateSystemConfig();

        return $this->success('操作成功');
    }

}
